import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store';
import { Message } from 'element-ui' // 导入 Message 组件

import LoginView from "@/views/LoginView.vue";
import AdminView from "@/views/AdminView.vue";
import WelcomeView from "@/views/WelcomeView.vue";
import UserView from "@/views/UserView.vue";
import RoleView from "@/views/RoleView.vue";

Vue.use(VueRouter)
// 路由配置
const routes = [
    {
        path: '/',
        name: 'login',
        component: LoginView
    },
    {
        path: '/admin',
        name: 'admin',
        component: AdminView,
        children: [
            {
                path: '',
                name: 'welcome',
                component: WelcomeView
            },
            {
                path: 'user',
                name: 'user',
                component: UserView
            },
            {
                path: 'role',
                name: 'role',
                component: RoleView
            }
        ]
    }
]
// 创建路由
const router = new VueRouter({
    routes
})
// 路由守卫
router.beforeEach((to, from, next) => {
    // 检查目标路由是否需要登录
    // 这个store是上方引入的store
    if (to.name !== 'login' && store.state.username === '') {
        // 弹框提示
        Message.error('请先登录'); // 使用导入的 Message

        // 未登录，重定向到登录页
        next({ name: 'login' });
    } else {
        // 已登录，继续导航
        next();
    }
});



export default router
